﻿using System;
using System.Web.UI;
using Acc.Lib;
using Data.UserDb;

namespace Acc_Web.controls
{
    public partial class UserCtrl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var usr = CookiesFunc.GetUserCookie();
                if (usr == null)
                {
                    loginPanel.Visible = true;
                    loginedPanel.Visible = false;
                }
                else
                {
                    loginPanel.Visible = false;
                    loginedPanel.Visible = true;
                    liUserName.Text = usr.UserName;
                    liVIP.Text = usr.IsVip ? "VIP会员" : "普通会员";

                    var respository = new ShopRepository();
                    var acc = respository.GetAccount(usr.UserId);
                    liAmount.Text = acc == null ? "0" : acc.Amount.ToString();
                }
            }
        }

        protected void sendLogin_Click(object sender, ImageClickEventArgs e)
        {
            if (String.IsNullOrEmpty(username.Text)) return;
            if (String.IsNullOrEmpty(psw.Text)) return;

            var ulib = new UserInfo();
            try
            {
                ulib.Login(username.Text, psw.Text);
                CookiesFunc.WriteUserCookie(ulib);
                Response.Redirect(Request.RawUrl);
            }
            catch (UserException ex)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "",
                                                        String.Format("alert('{0}');", ex.Message + ":" + ex.ErrorCode),
                                                        true);
            }
        }
    }
}